package com.wjh.anyview.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wjh.anyview.dao.RoleMapper;
import com.wjh.anyview.dao.UserRoleMapper;
import com.wjh.anyview.entity.po.Role;
import com.wjh.anyview.entity.po.UserRole;
import com.wjh.anyview.service.RbacService;
import com.wjh.anyview.service.constant.RoleConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author wjh
 * @date 2021/10/10 14:20
 * @Package com.wjh.anyview.service.impl
 */
@Service
@Slf4j
public class RbacServiceImpl implements RbacService {
    @Resource
    private RoleMapper roleMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    @Transactional
    public boolean setRole(String roleName, Long userId) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.eq("name", roleName);
        Role role = roleMapper.selectOne(wrapper);
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(role.getId());
        return userRoleMapper.insert(userRole) > 0;
    }

    @Override
    @Transactional
    public boolean setUserRole(Long userId) {
        return this.setRole(RoleConstant.USER, userId);
    }

    @Override
    @Transactional
    public boolean setStudentRole(Long userId) {
        return this.setRole(RoleConstant.STUDENT, userId);
    }

    @Override
    @Transactional
    public boolean setAdminRole(Long userId) {
        return this.setRole(RoleConstant.ADMIN, userId);
    }

}
